package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    /**
     * 登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据用户名查询用户信息，获取盐
         AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName,dto.getName())
//                .eq(AdUser::getStatus,AppHttpCodeEnum.ADCHANNEL_ADUSER_ISNOTEXIT_ERROR)
                .eq(AdUser::getStatus, AdminConstants.ADUSER_NORMAL_STATUS)
        );
        //判断用户信息是否为空
        if (adUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取数据库密码
        String pwd = adUser.getPassword();
        //获取密码
        String password = dto.getPassword();
        //获取盐
        String salt = adUser.getSalt();

        //3.加密并比对
        String hex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!pwd.equals(hex)){
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NAMEORPWD_ERROR);
        }

        //4.更新登录时间
        adUser.setCreatedTime(new Date());
        updateById(adUser);

        //5生成token和用户信息返回给前端
        HashMap<String, Object> resultMap = new HashMap<>();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        resultMap.put("token",token);

        //用户信息
        //不能将密码和盐返回
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user",adUser);
        //返回结果
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult register(AdUser user) {
        //1.参数校验
        if (user == null ||StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword())){
            //表示注册时的用户名或者密码为空
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.根据用户名查询
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
            .eq(AdUser::getName,user.getName())
        );
            //不为空表示用户名已存在
        if(adUser != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.ADMIN_USERNAME_EXIST);
        }
        //3.注册用户，生成盐(md5)
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        //获取密码+盐之后的加密密码
        String npwd = DigestUtils.md5DigestAsHex((user.getPassword() + salt).getBytes());
        user.setPassword(npwd);
        user.setSalt(salt);

        //设置用户状态为可登录
        user.setStatus(AdminConstants.ADUSER_NORMAL_STATUS);
        user.setCreatedTime(new Date());
        user.setLoginTime(new Date());

        //4.返回结果
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
